package javagames.render;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class RenderThreadExample extends JFrame implements Runnable{
	private volatile boolean running;
	private Thread gameThread;
	
	// Empty constructor
	public RenderThreadExample(){
		
	}
	
	protected void createAndShowGUI(){
		setSize(320,240);
		setTitle("Render Thread");
		setVisible(true);
		
		gameThread = new Thread(this);
		gameThread.start();
	}
	
	@Override
	public void run() {
		running = true;
		while (running){
			System.out.println("Game Loop");
			sleep(10);
		}
	}

	@SuppressWarnings("static-access")
	private void sleep(long sleep){
		try{
			gameThread.sleep(sleep);
		} catch (InterruptedException ex) { }		
	}
	
	protected void onWindowClosing(){
		try {
			System.out.println("Stopping Thread...");
			running = false;
			gameThread.join();
			System.out.println("Stopped!!");
		} catch (InterruptedException ex) { 
			ex.printStackTrace();
		}	
		System.exit(0);
	}
	
	public static void main(String[] args){
		final RenderThreadExample app = new RenderThreadExample();
		
		app.addWindowListener( new WindowAdapter() { 
			public void windowClosing(WindowEvent e) {
				app.onWindowClosing();
			}
		});
		
		SwingUtilities.invokeLater(new Runnable() {
			public void run(){
				app.createAndShowGUI();
			}	
		});
		
	}
}
	

